import traceback
from smtplib import SMTP_SSL
from email.header import Header
from email.mime.text import MIMEText

from submodules.common.lib.log_ import logger


def send_email(sub_type="plain", **kwargs):
    sender_config_list = kwargs["sender_config_list"]
    for i in range(len(sender_config_list)):
        sender_config = sender_config_list[i]
        try:
            # todo 参数检查
            sender = sender_config["sender"]
            receivers = kwargs["receivers"]

            message = MIMEText(_text=kwargs["text"], _subtype=f"{sub_type}", _charset='utf-8')
            message['from'] = sender_config["sender"]
            message['to'] = kwargs["to"]
            message['subject'] = Header(*kwargs["subject"])

            try:
                message['cc'] = kwargs["cc"]
            except:
                pass
            try:
                message['bcc'] = kwargs.get("bcc")
            except Exception as e:
                logger.error(repr(e))
                logger.error(traceback.format_exc())
            smtper = SMTP_SSL(sender_config["smtp_server"], 465)
            smtper.ehlo()
            # smtper.starttls()
            smtper.login(sender, sender_config["key"])
            smtper.sendmail(sender, receivers, message.as_string())
            logger.info("邮件发送完成！")
            break
        except Exception as e:
            logger.error(repr(e))
            logger.error(traceback.format_exc())


def send_email_html(**kwargs):
    send_email(sub_type="html", **kwargs)


def send_email_text(**kwargs):
    send_email(sub_type="plain", **kwargs)


def send_email_plain(**kwargs):
    send_email_text(**kwargs)


if __name__ == '__main__':
    def test_send_email_text():
        from config.private.private_config import email_info1
        send_email_text(**email_info1)


    def test_send_email_html():
        from config.private.private_config import email_info2
        send_email_html(**email_info2)


    # test_send_email_html()
    test_send_email_text()
